package com.laiketui.order;

import com.laiketui.core.lktconst.GloabConst;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.FastDateFormat;
import org.redisson.Redisson;
import org.redisson.api.RAtomicLong;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class OrderParentNoSeq {
    @Autowired
    private RedissonClient redisson;

    private static final String ORDER_PARENT_NO_SEQ = "order_parent_no_seq";
    private static final String ORDER_NO_SEQ = "order_no_seq";

    public String getOrderParentNo() {
        String format = FastDateFormat.getInstance(GloabConst.TimePattern.YMD1).format(new Date());
        RAtomicLong atomicLong = redisson.getAtomicLong(format + ORDER_PARENT_NO_SEQ);
        //设置一天过期
        atomicLong.expire(1, TimeUnit.DAYS);
        long l = atomicLong.incrementAndGet();
        return format+ StringUtils.leftPad(l+"",7,'0');
    }
    public String getOrderNo() {
        String format = FastDateFormat.getInstance(GloabConst.TimePattern.YMD5).format(new Date());
        RAtomicLong atomicLong = redisson.getAtomicLong(format + ORDER_NO_SEQ);
        //设置一天过期
        long l = atomicLong.incrementAndGet();
        if(l <= 0){
            atomicLong.expire(1, TimeUnit.DAYS);
        }
        return format+ StringUtils.leftPad(l+"",7,'0');
    }

    public List<String> getOrderNoList(int num) {
        String format = FastDateFormat.getInstance(GloabConst.TimePattern.YMD5).format(new Date());
        RAtomicLong atomicLong = redisson.getAtomicLong(format + ORDER_NO_SEQ);
        atomicLong.expire(1, TimeUnit.DAYS);
        long l = atomicLong.addAndGet(num);
        List<String> list = new ArrayList<>(num);
        for (long i = 0L; i < num; i++) {
            String s = StringUtils.leftPad(l-i + "", 7, '0');
            list.add(format+ s);
        }
        return list;
    }



}
